<?php
/**
 +------------------------------------------------------------------------------
 * FinanceAction控制器类
 +------------------------------------------------------------------------------
 * @category   财务
 * @package  app
 * @subpackage  Action
 * @author   朝闻道 <admin@iic.cn>
 * @date 2013-9-14
 * @time  下午2:44:22
 +------------------------------------------------------------------------------
 */
class FinanceAction extends BaseAction {
	protected $dao;
	/**
	 * 查看需要退款操作的订单
	 * @date 2013-9-14
	 * @time 下午2:50:02
	 */
	function index() {
		// 查看需要退款操作的订单
		$this->dao = D ( "FinanceV" );
		$where = array (
				'of.action' => array (
						'IN',
						"OOS,REFUND" 
				) 
		);
		if($_REQUEST['pay_status']){
			$status = $_REQUEST['pay_status'];
			if($_REQUEST['pay_status'] == 2){
				$status = 0;
			}
			$where['of.status'] = $status;
			$this->assign('status',$_REQUEST['pay_status']);
		}
		if($_REQUEST['platform']){	
			$where['of.platform'] = $_REQUEST['platform'];
			$this->assign('platform',$_REQUEST['platform']);
		}
		$action = array (
				'OOS' => '缺货退款',
				'REFUND' => '差价退款',
				'BUY' => '购买' 
		);
		$this->assign ( "action", $action );
		parent::index ( $where, $this->dao );
	} // end index
	
	/**
	 * 操作退款
	 * @date 2013-9-14
	 * @time 下午2:50:31
	 */
	function do_bak() {
		// 操作退款 缺货退款与差价退款
// 		$this->dao = D ( "FinanceV" );
		$arr = array (
				'OOS',
				'REFUND' 
		);
		$id = intval ( $_REQUEST ['id'] );
		$act = $_REQUEST ['act'];
		$userid = '';
		$orderid = $_REQUEST ['orderid'];
		$sn = $_REQUEST ['sn'];
		$platform = $_REQUEST ['platform'];
		
		if (! in_array ( $act, $arr )) {
			$this->_ajm ( '300', '操作类型错误。' );
		}
		//退货财务记录
		$order_finance = M ( "OrderFinance" );
		$where1 = array ();
		$where1 ['action'] = $act;
		$where1 ['id'] = $id;
		$where1 ['platform'] = 'SMW01';
		$where1 ['status'] = 0;
// 		$where1 ['ctime'] = mktime();
		$finance = $order_finance->where ( $where1 )->find ();
		if (empty ( $finance )) {
			$this->_ajm ( '300', '该退款操作已经处理或被取消。' );
		}
		//验证是否为退差价
		if($act == 'REFUND'){
			//退款
			$msg = $this->cut_payment($sn,$finance['value'],0,$finance['userid'],$platform);
			if ($msg) {
				$order_finance->where ( 'id=' . $finance ['id'] )->save ( array (
						'status' => 1
				) );
				$this->_ajm ( '200', '操作成功。', 1 );
			} else {
				$this->_ajm ( '300', '操作失败，请重试。' );
			}
		}else{
			
		//产品退款信息
		$where2 = array ();
		$where2 ['order_id'] = $finance['order_id'];
		$where2 ['platform'] = 'SMW01';
		$where2 ['goods_id'] =  intval($finance['goods_id']);
		$where2 ['code'] = 'refund';
		$orderfinance = $order_finance->where ( $where2 )->select ();
// 		dump($orderfinance);
// 		exit();
		foreach ($orderfinance as $v){
			//退款BV和CV
			if($v['subject'] == 'BV'){
				$bvrefund = $v['value'];
			}
			if($v['subject'] == 'CV'){
				$cvrefund = $v['value'];
				$userid=$v['action_userid'];
			}
		}
		$bvrefund = $finance['number'] * $bvrefund;
		$cvrefund = $finance['number'] * $cvrefund;
		
		
		//产品优惠信息
		$order_coupon = M ( "OrderCoupon" );
		$where5 = array ();
		$where5 ['order_id'] = $finance['order_id'];
		$where5 ['goods_id'] =  intval($finance['goods_id']);
		$ordercp = $order_coupon->where ( $where5 )->select();
		$couponCV=0;
		if($ordercp){
			foreach ($ordercp as $v){
				$couponCV+=$v['value'];
			}
			
		}
		//优惠产品数量
		$order_goods = M ( "OrderGoods" );
		$where8 = array ();
		$where8 ['order_id'] = $finance['order_id'];
		$where8 ['product_id'] = intval($finance['goods_id']);
		$ordergoods = $order_goods->where ( $where8 )->find ();
		//计算优惠产品金额
		$couponCV=($couponCV/$ordergoods['number'])*$finance['number'];
		//扣除优惠金额
		$cvrefund-=$couponCV;
		
		
		//订单当前财务记录
		$order_finance = M ( "OrderFinance" );
		$where3 = array ();
		$where3 ['order_id'] = $orderid;
		$where3 ['platform'] = 'SMW01';
		$where3 ['code'] = 'spotprice';
		$spotpricefinance = $order_finance->where ( $where3 )->select ();
		foreach ($spotpricefinance as $v){
			if($v['subject'] == 'BV'){
				$bvspotprice = $v['value'];
			}
			if($v['subject'] == 'CV'){
				$cvspotprice = $v['value'];
				
			}
			
		}
		
		if(($bvspotprice - $bvrefund) >= 0 && ($cvspotprice - $cvrefund) >= 0){
			$bvspotprice-=$bvrefund;
			$cvspotprice-=$cvrefund;
		}elseif(($cvspotprice - $cvrefund)>= 0){
			$bvrefund-=$bvspotprice;
			$bvspotprice = 0;
			$cvspotprice-=$cvrefund+$bvrefund;
			if($cvspotprice < 0){
				$this->_ajm ( '300', '操作失败，退款金额大于剩于金额，需要补差价。' );
			}
		}else{
			$this->_ajm ( '300', '操作失败，退款金额大于剩于金额，需要补差价。' );
		}
// 		$user_money = M ( "UserMoney" );
// 		$where = array ();
// 		$where ['order_id'] = $orderid;
// 		$where ['platform'] = 'SMW01';
// 		$where ['code'] = 'spotprice';
// 		$spotpricefinance = $order_finance->where ( $where )->find ();

		
		
// 		import ( 'Com.Money' );
// 		$money = new Money ();
// 		if ($data ['of_platform'] == 'SMW01') {
// 			// 云采购平台增加用户余额
// 			$nowvalue = $money->recharge ( $data ['of_userid'], $data ['subject'], $data ['value'] / 100, array (
// 					'action_userid' => $this->_userid,
// 					'cip' => get_client_ip (),
// 					'bzvu' => $data ['sn'] . ':' . $data ['remark'],
// 					'changtype' => 'ORDER_' . $data ['action'],
// 					'oper' => '+' 
// 			) );
// 		} elseif ($data ['of_platform'] == '91YUNGOU') {
// 			// 云购平台增加用户余额
// 			$nowvalue = $money->o2o_recharge ( $data ['of_userid'], $data ['subject'], $data ['value'] / 100, array (
// 					'action_userid' => $this->_userid,
// 					'cip' => get_client_ip (),
// 					'bzvu' => $data ['sn'] . ':' . $data ['remark'],
// 					'changtype' => 'ORDER_' . $data ['action'],
// 					'oper' => '+' 
// 			) );
// 		}
// 		dump($orderid);
// 		dump($cvrefund);
// 		dump($bvrefund);
// 		dump($userid);
// 		exit();
		//更新订单当前金额
		foreach ($spotpricefinance as $v){
			if($v['subject'] == 'BV'){
				$v['value'] = $bvspotprice;
				M('OrderFinance')->save($v);
			}
			if($v['subject'] == 'CV'){
				$v['value'] = $cvspotprice;
				M('OrderFinance')->save($v);
			}
		}
		//退款
		$msg = $this->cut_payment($sn,$cvrefund,$bvrefund,$userid,$platform);
		
		if ($msg) {
			$order_finance->where ( 'id=' . $finance ['id'] )->save ( array (
					'status' => 1 
			) );
			$this->_ajm ( '200', '操作成功。', 1 );
		} else {
			$this->_ajm ( '300', '操作失败，请重试。' );
		}
		}
	} // end do_bak
	/**
	 * 退款CV和BV
	 * @param CV $cvorder
	 * @param BV $bvorder
	 * @param ID $userid
	 * @return boolean
	 */
	function cut_payment($orderid,$cvorder,$bvorder,$userid,$platform){
	
		$usermoney=M('UserMoney');//用户金额
		$assetc_dao = M ( "UserAssets" );//流水
		$data=array();//数据集合
		$bvuser=0;//用户BV余额
		$cvuser=0;//用户CV余额
		$bvid = 0;//用户BV金额ID
		$cvid = 0;//用户CV金额ID
		//读取用户金额
		$usermoneys = M()->query( "select *	from user_money where userid = {$userid}" );
		foreach ($usermoneys as $um){
			//读取BV金额
			if($um['subject'] == 'BV' && $um['platform'] == $platform){
				$bvid=$um['id'];
				$bvuser = $um['value'];
			}
			//读取CV金额
			if($um['subject'] == 'CV' && $um['platform'] == $platform){
				$cvid=$um['id'];
				$cvuser = $um['value'];
			}
		}
		$assetc = array();
		$assetc['userid']=$userid;
		$assetc['action_userid']=$this->userid;//操作人员ID
		$assetc['platform']=$platform;//SMW01
		$assetc['ctime']=mktime();
		$assetc['cip']=get_client_ip();
		$assetc['bzvu']=$orderid;//备注信息:订单号、授权码、操作原因
		$assetc['changtype']='ORDER_BAK';//资金变动的原因 ORDER_USE ADMIN_ADD
// 		$usermoney->startTrans ();
// 		$assetc_dao->startTrans ();
	
		//更新BV金额
		
		$data["value"]=$bvuser+$bvorder;
		$assetc['value']=$bvorder;//变动数额
		$data['mtime']=mktime();
		if($bvid ==0){
			$data['platform']=$platform;
			$res=$usermoney->add($data);
		}else{
			$data["id"]=$bvid;
			$res=$usermoney->save($data);
		}
		
// 		if (!$res) {
// 			$usermoney->rollback ();
// 			return false;
// 		}
		// 写入充值流水
		$assetc['subject']='BV';//科目： BV CV CNY MV PV  COUPON
		$assetc['nowvalue']=$data["value"];//用户当前余额
		$assetc_id = $assetc_dao->add ( $assetc );
// 		if (!$assetc_id) {
// 			$usermoney->rollback ();
// 			$assetc_dao->rollback ();
// 			return false;
// 		}
	
		//更新CV金额
		$data["value"]=$cvuser + $cvorder;
		$data['mtime']=mktime();
		if($cvid ==0){
			$data['platform']=$platform;
			$res=$usermoney->add($data);
		}else{
			$data["id"]=$cvid;
			$res=$usermoney->save($data);
		}
// 		if (!$res) {
// 			$usermoney->rollback ();
// 			$assetc_dao->rollback ();
// 			return false;
// 		}
		// 写入充值流水
		$assetc['subject']='CV';//科目： BV CV CNY MV PV  COUPON
		$assetc['value']=$cvorder;//变动数额
		$assetc['nowvalue']=$cvuser + $cvorder;//用户当前余额
		$assetc_id = $assetc_dao->add ( $assetc );
// 		if (!$assetc_id) {
// 			$usermoney->rollback ();
// 			$assetc_dao->rollback ();
// 			return false;
// 		}
// 		$usermoney->commit ();
// 		$assetc_dao->commit ();
		return true;
	}
	/**
	 * 云购订单结算
	 * @date 2013-12-12
	 * @time 下午2:44:40
	 */
	function o2o_fee() {
		// 云购订单结算
	} // end o2o_fee
	
	/**
	 * 资金结款操作
	 * @date 2013-12-12
	 * @time 下午2:45:06
	 */
	function do_o2o_fee() {
		// 资金结款操作
	} // end do_o2o_fee
	
	/**
	*购物车未购买的商品统计
	*/
	function gouw(){
	
	    $gouw = M('cart_o2o'); 
		$datetime = strtotime($_REQUEST['ktime']);
		$endtime = strtotime($_REQUEST['jtime']);
		$uname  = $_REQUEST['uname'];
		$sfield = $_REQUEST['sfield'];
		$where = array();
		if(!empty($datetime) && empty($endtime)){
			$where['ctime'] = array('egt',$datetime);
		}elseif(!empty($datetime) && !empty($endtime)){
			$where['ctime'] = array(array('egt',$datetime),array('elt',$endtime),'and');
		}
		if(!empty($uname) && $sfield!='all'){
			$where[$sfield] = array('like',"%{$uname}%");
		}
		$where['status'] = 1;
		$count = $gouw->where($where)->count();
		$Page = new Page( $count,$this->listrows );
		$result = $gouw->field('user_id,product_thumb,product_name,price,number,ctime')->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();
		//echo $gouw->getLastSql();
		$show  = $Page->show();// 分页显示输出
		//$this->assign('pages',$show);
		//echo $gouw->getLastSql();
		$this->assign('ktime',$datetime);
		$this->assign('jtime',$endtime);
		$this->assign('stype',$sfield);
		$this->assign('uname',$uname);
		$this->assign('result',$result);
		$this->assign('totalCount',$count);
		
		$this->display();
	}
	
	function delall(){
		$dao = M('order_finance');
		$res=$dao->where(array('id'=>$_REQUEST['id']))->delete();
		if($res===FALSE){
			$this->_ajm(300,'操作错误，请重试');
		}else{
			$this->_ajm(200,'操作成功',1,U(MODULE_NAME.'/index'));
		}		
	}
	
	
	
	
}//end FinanceAction